﻿using System.Linq;
using Microsoft.Practices.ServiceLocation;
using Reactor.Contracts;
using Reactor.Environment;

namespace Reactor
{
    public static class ServiceLocatorExtensions
    {
        private static IServiceRegistrar _registrar;

        /// <summary>
        /// Registers a single instance that is to be returned when the specified type is requested..
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceLocator">The service locator.</param>
        /// <param name="instance">The instance.</param>
        public static void RegisterInstance<T>(this IServiceLocator serviceLocator, object instance) where T : class
        {
            if (_registrar == null) _registrar = Context.ServiceLocator.GetInstance<IServiceRegistrar>();

            _registrar.RegisterInstance<T>(instance);
        }

        /// <summary>
        /// Registers the a concrete type to associate with the abstract type.
        /// </summary>
        /// <typeparam name="T">Abstract type</typeparam>
        /// <typeparam name="TConcrete">The concrete type to instantiate when the abstract type is requested.</typeparam>
        /// <param name="serviceLocator">The service locator.</param>
        public static void RegisterType<T, TConcrete>(this IServiceLocator serviceLocator) where T : class where TConcrete : T
        {
            if (_registrar == null) _registrar = Context.ServiceLocator.GetInstance<IServiceRegistrar>();

            _registrar.RegisterType<T, TConcrete>();
        }

        /// <summary>
        /// Returns boolean indicator stating whether or not the specified type contains a mapping in the service locator.
        /// </summary>
        /// <typeparam name="T">The type to search the service locator for.</typeparam>
        /// <param name="serviceLocator">The service locator.</param>
        /// <returns>Boolean indicator</returns>
        public static bool TypeMapExists<T>(this IServiceLocator serviceLocator)
        {
            var instances = Context.ServiceLocator.GetAllInstances(typeof(T));
            return instances.Count() > 0;
        }
    }
}
